<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
  <title>管理员登录</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
  <link rel="stylesheet" href="./css/managerLogin.css">
</head>
<body>
<div class="login-container">
  <div class="login-header">
    <h2><i class="fa fa-lock"></i> 管理员登录</h2>
    <p>欢迎使用管理系统</p>
  </div>

  <form id="loginForm" method="post" onsubmit="return handleFormSubmit(event)">
    <input type="hidden" name="action" value="register">
    <div class="form-group">
      <div class="input-icon">
        <i class="fa fa-user"></i>
        <input type="text" id="username" name="username" required>
        <label for="username">用户名</label>
      </div>
    </div>
    <div class="form-group">
      <div class="input-icon">
        <i class="fa fa-key"></i>
        <input type="password" id="password" name="password" required>
        <label for="password">密码</label>
      </div>
    </div>
    <div class="form-options">
      <label>
        <input type="checkbox" name="remember"> 记住我
      </label>
      <a href="#" class="forgot-password">忘记密码？</a>
    </div>
    <div id="message" class="message"></div>
    <button type="submit" class="login-button">
      <span class="button-text">注册</span>
      <i class="fa fa-arrow-right"></i>
    </button>
    <div class="register-link">
      已有账号？ <a href="managerLogin.jsp">立即登录</a>
    </div>
  </form>
</div>

<script>
  async function handleFormSubmit(event) {
    event.preventDefault();

    const formData = new URLSearchParams(new FormData(event.target));
    const submitBtn = event.target.querySelector('button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.innerHTML = `<i class="fa fa-spinner fa-spin"></i> 登录中...`;

    try {
      const response = await fetch('adminLoginServlet', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: formData
      });

      const data = await response.json();
      if (data.status === 'success') {
        window.location.href = 'admin.jsp'; // 跳转到管理后台
      } else {
        showMessage(data.message || '登录失败', 'error');
      }
    } catch (error) {
      showMessage('网络连接错误，请稍后重试', 'error');
    } finally {
      submitBtn.disabled = false;
      submitBtn.innerHTML = `<span class="button-text">登录</span><i class="fa fa-arrow-right"></i>`;
    }
  }

  function showMessage(text, type = 'error') {
    const messageEl = document.getElementById('message');
    messageEl.textContent = text;
    messageEl.className = `message ${type}`;
    messageEl.style.display = 'block';

    setTimeout(() => {
      messageEl.style.opacity = '0';
      setTimeout(() => messageEl.style.display = 'none', 500);
    }, 3000);
  }
</script>
</body>
</html>